﻿package tools;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyDemo {
	public static void main(String[] args) {

		Hole hole = new ProxyHole(new SmallHole());
		hole.plugIn(true);

		Hole sph = (Hole) new SuperProxyHole().bind(new SmallHole());
		sph.plugIn(false);
	}
}

interface Hole {
	public void plugIn(boolean withDurex);
}

class SmallHole implements Hole {

	@Override
	public void plugIn(boolean withDurex) {
		if (withDurex) {
			System.out.println("PlugIn SmallHole withDurex");
		} else {
			System.out.println("PlugIn SmallHole withoutDurex");
		}
	}
}

/** 常规代理 */
class ProxyHole implements Hole {
	private Hole hole = null;

	ProxyHole(Hole hole) {
		this.hole = hole;
	}

	@Override
	public void plugIn(boolean withDurex) {
		System.out.println("proxy is doing sth.");
		hole.plugIn(withDurex);
	}
}

/** 超级代理,可以代理任意接口(通过反射实现) */
class SuperProxyHole implements InvocationHandler {
	Object obj = null;

	public Object bind(Object obj) {
		/** 获得真实类对象 */
		this.obj = obj;
		/** 动态返回一个代理 */
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
				.getClass().getInterfaces(), this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		/** 调用真实类(this.obj)对象的方法 */
		Object obj = method.invoke(this.obj, args);
		return obj;
	}

}
